package com.z;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * @ProjectName: springboot-08-shiro
 * @Package: PACKAGE_NAME
 * @ClassName: TestShiroSercurityManager
 * @author: Arisapoke
 * @date: 2021/2/2 16:45
 * @Version: 1.0
 */
public class TestShiroSercurityManager {

    public static void main(String[] args) {
        //1. new DefaultSecurityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        //2. 给安全管理器设置realm
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));

        //3. SecurityUtils 给安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //4. 关键对象 subject 主体
        Subject subject = SecurityUtils.getSubject();

        //5. 创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("chenhui", "123456");

        //6. 用户认证
        try {
            System.out.println(subject.isAuthenticated());
            subject.login(token);
            System.out.println(subject.isAuthenticated());
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("username error");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
        }
    }
}
